package com.hanxiaozhang.base.controller;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hanxiaozhang.annotation.EnableGlobalException;
import com.hanxiaozhang.base.entity.TableEntity;
import com.hanxiaozhang.base.service.GeneratorService;
import com.hanxiaozhang.exception.InternalServerException;
import com.hanxiaozhang.result.Result;
import com.hanxiaozhang.util.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 生成代码
 *
 * @author hanxiaozhang
 * @email hanxiaozhang2018@sina.com
 * @date 2021-04-23
 */
@Slf4j
@Controller
@RequestMapping("/generator")
@EnableGlobalException
public class GeneratorController {


    @Autowired
    private GeneratorService generatorService;


    @ResponseBody
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('tool:generator:list')")
    public Result<PageUtil> list(@RequestParam Map<String, Object> params) {

        Page<TableEntity> page = PageHelper
                .startPage(Integer.parseInt(params.get("current").toString()), Integer.parseInt(params.get("pageSize").toString()));
        List<TableEntity> tableList = generatorService.listTable();
        return Result.success(new PageUtil(tableList, (int) page.getTotal()));
    }


    @ResponseBody
    @GetMapping("/getConfig")
    @PreAuthorize("hasAuthority('tool:generator:list')")
    public Result getConfig() {
        return Result.success(generatorService.getConfig());
    }


    @ResponseBody
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('tool:generator:update')")
    public Result<Void> update(@RequestBody Map<String, Object> params) {

        generatorService.updateConfig(params);
        return Result.success();
    }

    @PostMapping("/download/code")
    @PreAuthorize("hasAuthority('tool:generator:code')")
    public void code(HttpServletResponse response, String tableName) {
        try {
            List<String> tableNames = new ArrayList<>();
            tableNames.add(tableName);
            commonCode(response, tableNames);
        } catch (IOException e) {
            log.error("生成代码流异常,异常信息:[{}}", e.getMessage());
            throw new InternalServerException(e.getMessage());
        }
    }


    @RequestMapping("/download/batchCode")
    @PreAuthorize("hasAuthority('tool:generator:batchCode')")
    public void batchCode(HttpServletResponse response, @RequestParam("tableNames") List<String> tableNames) {
        try {
            commonCode(response, tableNames);
        } catch (IOException e) {
            log.error("批量生成代码流异常,异常信息:[{}}", e.getMessage());
            throw new InternalServerException(e.getMessage());
        }
    }


    /**
     * 生产代码公共
     *
     * @param response
     * @param tableNames
     * @throws IOException
     */
    private void commonCode(HttpServletResponse response, List<String> tableNames) throws IOException {
        byte[] data = generatorService.generatorCode(tableNames);
        response.reset();
        response.setContentType("application/zip;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"generatorCode.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        //使用Content-Disposition,一定要确保没有禁止浏览器缓存的操作
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "No-cache");
        response.setDateHeader("Expires", 0);
        IOUtils.write(data, response.getOutputStream());
    }


}
